package cn.ssm.controller;

import java.text.Format.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import cn.ssm.biz.impl.ClassroomBizImpl;
import cn.ssm.biz.impl.CompInfoBizImpl;
import cn.ssm.biz.impl.ComputerroomBizImpl;
import cn.ssm.biz.impl.CoursesBizImpl;
import cn.ssm.biz.impl.FaultBizImpl;
import cn.ssm.biz.impl.RepairListBizImpl;
import cn.ssm.pojo.Class;
import cn.ssm.pojo.Computerroom;
import cn.ssm.pojo.Fault;
import cn.ssm.pojo.Pager;
import cn.ssm.query.ComputerQuery;
import cn.ssm.query.CoursesQuery;
import cn.ssm.query.RepairCountQuery;

@Controller
@RequestMapping("/FaultController")
public class FaultController {

	@Autowired
	@Qualifier("computerroomBizImpl")
	private ComputerroomBizImpl com;

	@Autowired
	@Qualifier("ClassroomBizImpl")
	private ClassroomBizImpl classroomBizImpl;

	@Autowired
	@Qualifier("FaultBizImpl")
	private FaultBizImpl faultBizImpl;

	@Autowired
	@Qualifier("CImpl")
	private CompInfoBizImpl CIBI;

	@Autowired
	@Qualifier("RImpl")
	private RepairListBizImpl RImpl;

	@Autowired
	@Qualifier("coursesBizImpl")
	private CoursesBizImpl coursesBizImpl;

	@RequestMapping("/findFault")
	public String findFault(ModelMap modelMap, HttpServletRequest request) {
		String currentPageStr = request.getParameter("currentPage");
		System.out.println(currentPageStr);
		int rowCount = faultBizImpl.selectfaultCount();
		Pager pager = null;
		if (currentPageStr == null) {
			pager = new Pager(rowCount, 5, 1);
		} else {
			int currentPage = Integer.parseInt(request.getParameter("currentPage"));
			pager = new Pager(rowCount, 5, currentPage);
		}

		pager.setUrl("/FaultController/findFault");
		List<Fault> faultList = faultBizImpl.faultInfo(pager);

		System.out.println("===================" + faultList.size());
		modelMap.addAttribute("faultList", faultList);
		modelMap.put("pager", pager);
		return "fault";

	}

	@RequestMapping("/delFault")
	public String delFault(int id) {
		int num = faultBizImpl.deleteFault(id);
		System.out.println("del");
		String url = "";
		if (num > 0) {
			url = "redirect:/FaultController/findFault";
		} else {
			url = "404";
		}
		return url;
	}

	@RequestMapping("/addFault")
	public String addFault(ModelMap mo, @RequestParam String faultName, @RequestParam String faultType) {

		Fault f = new Fault();
		f.setFaultName(faultName);
		f.setFaultType(faultType);
		int num = faultBizImpl.addfaultInfo(f);
		String url = "";
		if (num > 0) {
			url = "redirect:/FaultController/findFault";
		} else {
			url = "faultAdd";
		}
		return url;
	}

	/**
	 * 
	 * 获取损坏的统计信息
	 * 
	 * @param mo
	 * @param computerroomId
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	@RequestMapping("/findFaultRoom")
	public String findFaultRoom(ModelMap mo, Integer computerroomId, String startDate, String endDate,
			Integer classroomId) {

		List<Computerroom> computerroomList = com.getRoomdescribe();
		System.out
				.println("====================findFaultRoom================================" + computerroomList.size());
		mo.put("computerroomList", computerroomList);
		List<Class> classroomInfo = classroomBizImpl.classroomInfo1();
		mo.put("classroomInfo", classroomInfo);

		computerroomId = null == computerroomId || computerroomId == 0 ? null : computerroomId;
		startDate = null == startDate || "".equals(startDate) ? null : startDate;
		endDate = null == endDate || "".equals(endDate) ? null : endDate;
		classroomId = null == classroomId || classroomId == 0 ? null : classroomId;

		// SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");

		// 对应9种损坏情况
		Map<Long, Integer> countMap = new HashMap<Long, Integer>();
		List<Fault> faultInfo1 = faultBizImpl.faultInfo1();
		for (Fault fault : faultInfo1) {
			countMap.put(Long.valueOf(fault.getId()), 0);
		}
		mo.put("faultInfo1", faultInfo1);

		// startDate==null?null:sdf.format(startDate), endDate==null ?
		// null:sdf.format(endDate)
		List<RepairCountQuery> selectCountByFaultId = RImpl.selectCountByFaultId(computerroomId, null, null, startDate,
				endDate, classroomId);

		for (RepairCountQuery repairCountQuery : selectCountByFaultId) {

			countMap.put(repairCountQuery.getFaultId().longValue(), repairCountQuery.getCountNum());
		}

		mo.put("countMap", countMap);

		return "tongjitu";
	}

	/**
	 * 
	 * 获取损坏的统计信息（异步方法）
	 * 
	 * @param mo
	 * @param computerroomId
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/findFaultRoom2")
	public String findFaultRoom2(ModelMap mo, Integer computerroomId, String startDate, String endDate,
			Integer classroomId) {

		try {

			ComputerQuery selComputer = null;

			if (classroomId != null && classroomId != 0) {

				Class selectByID = classroomBizImpl.selectByID(classroomId);
				CoursesQuery selCourseById = coursesBizImpl.selCourseByClassId(selectByID.getId());
				String periodName = getPeriodName(selCourseById.getPeroidId());
				// 获取本班级的下一个班
				selComputer = CIBI.selComputer(periodName, selectByID.getComputerroom().getId(), null);
			}

			computerroomId = null == computerroomId || computerroomId == 0 ? null : computerroomId;
			startDate = null == startDate || "".equals(startDate) ? null : startDate;
			endDate = null == endDate || "".equals(endDate) ? null : endDate;
			classroomId = null == classroomId || classroomId == 0 ? null : selComputer.getClassId();

			// SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");

			// 对应9种损坏情况
			Map<Long, Integer> countMap = new HashMap<Long, Integer>();

			List<Fault> faultInfo1 = faultBizImpl.faultInfo1();
			for (Fault fault : faultInfo1) {
				countMap.put(Long.valueOf(fault.getId()), 0);
			}
			mo.put("faultInfo1", faultInfo1);

			List<RepairCountQuery> selectCountByFaultId = RImpl.selectCountByFaultId(computerroomId, null, null,
					startDate, endDate, classroomId);

			for (RepairCountQuery repairCountQuery : selectCountByFaultId) {

				countMap.put(repairCountQuery.getFaultId().longValue(), repairCountQuery.getCountNum());
			}

			List<Integer> countList = new ArrayList<Integer>();

			for (Long integer : countMap.keySet()) {
				countList.add(countMap.get(integer));
			}
			return JSONObject.toJSONString(countList);

		} catch (Exception e) {
			// TODO: handle exception
			return "{\"mess\":\"err\"}";
		}

	}

	public String getPeriodName(Integer id) {

		Map<Integer, String> maps = new HashMap<Integer, String>();
		maps.put(1, "一三五上午");
		maps.put(2, "一三五下午");
		maps.put(3, "二四六上午");
		maps.put(4, "二四六下午");
		maps.put(5, "星期日上午");
		maps.put(6, "星期日下午");

		return maps.get((id + 1) > 6 ? 1 : (id + 1));

	}

	/**
	 * 
	 * 获取损坏的统计信息_所有损坏
	 * 
	 * @param mo
	 * @param computerroomId
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	@RequestMapping("/findFaultRoom3")
	public String findFaultRoom3(ModelMap mo, Integer computerroomId, String startDate, String endDate,
			Integer classroomId) {

		List<Computerroom> computerroomList = com.getRoomdescribe();
		System.out
				.println("====================findFaultRoom================================" + computerroomList.size());
		mo.put("computerroomList", computerroomList);
		List<Class> classroomInfo = classroomBizImpl.classroomInfo1();
		mo.put("classroomInfo", classroomInfo);
		computerroomId = null == computerroomId || computerroomId == 0 ? null : computerroomId;
		startDate = null == startDate || "".equals(startDate) ? null : startDate;
		endDate = null == endDate || "".equals(endDate) ? null : endDate;
		classroomId = null == classroomId || classroomId == 0 ? null : classroomId;

		// SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");

		// 对应9种损坏情况

		Map<Integer, String> countMap1 = new HashMap<Integer, String>();
		List<Fault> faultInfo1 = faultBizImpl.faultInfo1();
		for (Fault fault : faultInfo1) {

			countMap1.put(fault.getId(), fault.getFaultName());

		}

		List<RepairCountQuery> selectCountByFaultId = RImpl.selectCountByFaultId4(computerroomId, null, null, startDate,
				endDate, classroomId);

		Map<String, Integer> countMap = new HashMap<String, Integer>();
		for (RepairCountQuery repairCountQuery : selectCountByFaultId) {

			countMap.put(countMap1.get(repairCountQuery.getFaultId()), repairCountQuery.getCountNum());
		}

		mo.put("faultInfo1", faultInfo1);
		mo.put("countMap", countMap);

		return "tongjitu2";
	}

	/**
	 * 查看所有的班级的损坏统计
	 * 
	 * @param mo
	 * @param computerroomId
	 * @param startDate
	 * @param endDate
	 * @param classroomId
	 * @return
	 */

	@RequestMapping("/findFaultRoom4")
	public String findFaultRoom4(ModelMap mo, Integer computerroomId, String startDate, String endDate,
			Integer classroomId) {

		try {

			ComputerQuery selComputer = null;

			List<Class> classroomInfo1 = classroomBizImpl.classroomInfo1();

			Map<String, List<String>> resultMap = new HashMap<String, List<String>>();

			for (Class cls : classroomInfo1) {

				Class selectByID = classroomBizImpl.selectByID(cls.getId());
				CoursesQuery selCourseById = coursesBizImpl.selCourseByClassId(selectByID.getId());

				if (selCourseById != null) {
					String periodName = getPeriodName(selCourseById.getPeroidId());

					// 获取本班级的下一个班
					selComputer = CIBI.selComputer(periodName, selectByID.getComputerroom().getId(), null);

					//发现下一个班级为空的话就循环，一直到不为空，比如 当前班级的上个时段id为3
					//就会按照  4-5-6-1-2-3 的顺序去查找   如果找不到就会回到原始的3，3肯定查的当前的班级
					for (int i = 1; i <= 6 && null == selComputer; i++) {

						periodName = getPeriodName((selCourseById.getPeroidId() + i) > 6 ? i - selCourseById.getPeroidId(): (selCourseById.getPeroidId() + i));
						selComputer = CIBI.selComputer(periodName, selectByID.getComputerroom().getId(), null);

					}

					// SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");

					// 对应9种损坏情况
					Map<Long, String> countMap = new HashMap<Long, String>();
					// countMap.put(1l, "");
					// countMap.put(2l, "");
					// countMap.put(3l, "");
					// countMap.put(11l, "");
					// countMap.put(5l, "");
					// countMap.put(6l, "");
					// countMap.put(7l, "");
					// countMap.put(8l, "");
					// countMap.put(9l, "");

					List<Fault> faultInfo1 = faultBizImpl.faultInfo1();
					for (Fault fault : faultInfo1) {
						countMap.put(Long.valueOf(fault.getId()), "无");
					}
					mo.put("faultInfo1", faultInfo1);

					// startDate==null?null:sdf.format(startDate), endDate==null ?
					// null:sdf.format(endDate)

					if (selComputer != null) {
						classroomId = selComputer.getClassId();
						List<RepairCountQuery> selectCountByFaultId = RImpl.selectCountByFaultId4(computerroomId, null,
								null, startDate, endDate, classroomId);

						for (int i = 0; i < selectCountByFaultId.size() && classroomId != null; i++) {

							countMap.put(selectCountByFaultId.get(i).getFaultId().longValue(),
									selectCountByFaultId.get(i).getCountNum().toString());
						}

						System.out.println(
								countMap.toString() + "=======================================" + cls.getClassName());

						List<String> countList = new ArrayList<String>();

						for (Long integer : countMap.keySet()) {
							countList.add(countMap.get(integer));
						}
						resultMap.put(cls.getClassName(), countList);
					} else {
						List<String> countList = new ArrayList<String>();
						for (int i = 0; i < countMap.size(); i++) {

							countList.add("无");
						}
						resultMap.put(cls.getClassName(), countList);
					}

				} else {

					Map<Long, String> countMap = new HashMap<Long, String>();
					List<Fault> faultInfo1 = faultBizImpl.faultInfo1();
					for (Fault fault : faultInfo1) {
						countMap.put(Long.valueOf(fault.getId()), "无");
					}
					mo.put("faultInfo1", faultInfo1);

					List<String> countList = new ArrayList<String>();
					for (int i = 0; i < countMap.size(); i++) {

						countList.add("无");
					}
					resultMap.put(cls.getClassName(), countList);

				}

			}

			mo.put("classroomInfo", classroomInfo1);
			mo.put("resultMap", resultMap);

			return "tongjitu3";

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			mo.put("mess", "err");
			return "tongjitu3";
		}

	}

}
